<?php
include_once('config/config.php');
if ($_POST) {
  $params = $_POST;
  $action = $_POST['action'];
  if ($action == 'checkName') {
    $username = $_POST['username'];
    if (empty(trim($username))) {
      error('用户名不能为空');
    }
    $depId = dbFind("SELECT `id` FROM `admin` WHERE `username` = '$username'");
    if ($depId) {
      error('用户已经存在');
    } else {
      success('用户可以使用');
    }
  }

  if ($params['password'] != $params['rePassword']) {
    ShowMsg('密码与确认密码不一致');
    exit;
  }

  //密码盐
  $salt = build_ranstr();
  if (!$salt) {
    ShowMsg('密码盐必填');
    exit;
  }
  $password = md5($params['password'] . $salt);

  $avatar = upload('avatar');

  //检查上传图片的数据
  if ($avatar['code'] == 0) {
    ShowMsg($avatar['msg']);
    exit;
  }

  //封装数组
  $data = [
    'username' => $params['username'],
    'password' => $password,
    'avatar' => $avatar['data'],
    'salt' => $salt,
  ];
  //新增新数据到数据库
  $res = dbAdd('admin', $data);
  if ($res) {
    ShowMsg('新增成功', 'adminList.php');
    exit;
  } else {
    ShowMsg('新增失败');
    exit;
  }
  //返回新增成功的新增id
  // pre($res);

  exit;
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>管理员</title>
  <!-- 引用公共头部 -->
  <?php include_once('common/meta.php'); ?>

  <style>
    #avatar {
      width: 200px;
      user-select: none;
    }

    #img {
      width: 200px;
      display: block;
    }

    .icon-list {
      margin-right: 5px;
    }
  </style>
</head>

<body>

  <!-- 引用公共头部 -->
  <?php include_once('common/header.php'); ?>

  <!-- 引用侧边菜单 -->
  <?php include_once('common/sidebar.php'); ?>

  <div class="content">
    <div class="header">
      <h1 class="page-title">新增管理员</h1>
    </div>
    <ul class="breadcrumb">
      <li><a href="index.php">首页</a> <span class="divider">/</span></li>
      <li class="active">管理员</li>
    </ul>

    <div class="container-fluid">
      <div class="row-fluid">

        <div class="btn-toolbar">
          <button class="btn btn-primary " onClick="location='adminList.php'"><i class="icon-list"></i>管理员</button>
          <div class="btn-group">
          </div>
        </div>

        <div class="well">
          <div id="myTabContent" class="tab-content">
            <div class="tab-pane active in" id="home">
              <form method="POST" enctype="multipart/form-data">

                <label>用户名</label>
                <input type="text" value="" class="input-xxlarge" name="username" placeholder="请输入用户名" required>
                <span id="username" style="margin-left: 10px;"></span>

                <label>密码</label>
                <input type="password" value="" class="input-xxlarge" name="password" placeholder="请输入密码" required>

                <label>确认密码</label>
                <input type="password" value="" class="input-xxlarge" name="rePassword" placeholder="请输入确认密码" required>

                <label>头像</label>
                <input type="file" value="" class="input-xxlarge" id="avatar" name="avatar" hidden required>
                <label class="avatar" for="avatar">
                  <img src="static/images/upload.png" id="img">
                  <!-- <button class="btn btn-primary" type="button">选择文件</button> -->
                </label>

                <input class="btn btn-primary" type="submit" value="提交" />
              </form>
            </div>
          </div>
        </div>

        <!-- 引用公共底部 -->
        <?php include_once('common/footer.php'); ?>

      </div>
    </div>
  </div>
</body>

</html>
<!-- 引用script -->
<?php include_once('common/script.php'); ?>
<script>
  // 图片预览函数
  function GetObjectURL(file) {
    // createObjectURL  给一个文件对象 可以提取出一个url本地地址出来
    var url = null;

    //判断是否为IE浏览器还是google还是其他浏览器
    if (window.createObjectURL != undefined) {
      url = window.createObjectURL(file)
    } else if (window.URL != undefined) {
      url = window.URL.createObjectURL(file)
    } else if (window.webkitURL != undefined) {
      url = window.webkitURL.createObjectURL(file)
    }

    return url
  }
  $('#avatar').change(function() {

    // 获取选中的文件
    let file = $(this)[0].files[0] ? $(this)[0].files[0] : {};


    // 获取文件地址
    let url = GetObjectURL(file)
    $('#img').attr('src', url);
  });

  $('input[name="username"]').change(function() {
    let username = $(this).val();

    $.ajax({
      type: 'post',
      url: 'adminAdd.php',
      data: {
        username,
        action: 'checkName'
      },
      dataType: 'json',
      success: function(res) {
        if (res.code === 1) {
          $('#username').html(res.msg).css({
            "color": "green"
          })
        } else {
          $('#username').html(res.msg).css({
            "color": "red"
          })
        }
      },
      // 请求失败的回调函数 404 301 500等
      error: function(error) {
        console.log(error)
      }
    })
  });
</script>